<?php defined('SYSPATH') or die('No direct script access.');

/**
 * Class Model_Finance_Income
 */
class Model_Finance_Income extends ORM
{
    protected $_table_name = 'platform_income';
    /**
     * @var array 到账状态
     */
    public static $account_status = array('待确认', '已到账');

    /**
     * @function 通过订单号获取收入记录
     * @param $ordersn
     * @return mixed
     */
    public static function get_info_by_ordersn($ordersn)
    {
        return DB::select()
                 ->from('platform_income')
                 ->where('ordersn', '=', $ordersn)
                 ->execute()
                 ->current();
    }

    /**
     * @function 保存收入记录
     * @param array  $arr
     * @param string $id
     * @return bool
     */
    public static function save_info(array $arr, $id = '')
    {
        $ordersn = $arr['ordersn'];
        if (! $ordersn)
        {
            return false;
        }
        unset($arr['ordersn']);
        if ($id)
        {
            $orm = ORM::factory('finance_income', $id);
        }
        else
        {
            if (self::get_info_by_ordersn($ordersn))
            {
                $orm = ORM::factory('finance_income')
                          ->where('ordersn', '=', $ordersn)
                          ->find();
            }
            else
            {
                $orm = ORM::factory('finance_income');
                $orm->ordersn = $ordersn;
            }
        }
        foreach ($arr as $k => $v)
        {
            $orm->$k = $v;
        }

        $orm->save();
        if ($orm->saved())
        {
            return true;
        }

        return false;
    }

    /**
     * @function 获取所有可买产品模型
     * @return mixed
     */
    public static function get_all_pdt_modules()
    {
        return DB::select('id', 'modulename', 'pinyin','maintable','correct')
                 ->from('model')
                 ->where('is_orderable', '=', 1)
                 ->execute()
                 ->as_array();
    }

    /**
     * @function 获取支付方式
     * @return mixed
     */
    public static function get_pay_sources()
    {
        return DB::select('paysource')
                 ->distinct('paysource')
                 ->from('member_order')
                 ->where('paysource', 'IS NOT', null)
                 ->execute()
                 ->as_array();
    }

    /**
     * @function 获取总记录数
     * @return mixed
     */
    public static function get_total_count($params)
    {
        $sql = 'SELECT COUNT(a.`id`) AS `total`';
        $sql .= 'FROM `sline_platform_income` AS `a` ';
        $sql .= 'LEFT JOIN `sline_member_order` AS b ON(a.`ordersn` = b.`ordersn`) ';
        $sql .= 'LEFT JOIN `sline_model` AS `c` ON(a.`type_id` = c.`id`) ';
        $sql .= 'WHERE 1 = 1 ';
        if ($params['type_id'])
        {
            $sql .= 'AND a.`type_id` = ' . $params['type_id'] . ' ';
        }
        if ($params['channel_id'])
        {
            $sql .= 'AND b.`channel_id` = ' . $params['channel_id'] . ' ';
        }
        if ($params['pay_type'])
        {
            $sql .= 'AND a.`pay_type` = \'' . $params['pay_type'] . '\' ';
        }
        if ($params['status'] != '')
        {
            $sql .= 'AND a.`status` = ' . $params['status'] . ' ';
        }
        if ($params['keyword'])
        {
            $sql .= "AND (a.`ordersn` LIKE '%{$params['keyword']}%' OR a.`linkman` LIKE '%{$params['keyword']}%' OR a.`linktel` LIKE '%{$params['keyword']}%') ";
        }

        return DB::query(1, $sql)->execute()->get('total', 0);
    }

    /**
     * @function 平台收入列表
     * @param array $array
     * @return mixed
     */
    public static function get_search_list(array $array = array())
    {
        $sql = 'SELECT a.`id`,a.`ordersn`,a.`type_id`,a.`amount`,a.`mid`,a.`pdt_type`,a.`pay_type`,';
        $sql .= 'a.`pdt_name`,a.`pay_time`,a.`status`,a.`operator`,b.online_transaction_no,a.`opt_time`,a.`amount`,';
        $sql .= 'c.`pinyin`,c.`correct`,b.`id` AS `orderid`,';
        $sql .= 'b.`online_transaction_no` AS `pay_num`,';
        $sql .= 'b.`payment_proof` AS `pay_proof`,';
        $sql .= 'b.`saleman` AS `salesman`,';
        $sql .= 'b.`linkman`,';
        $sql .= 'b.`linktel` ';
        $sql .= 'FROM `sline_platform_income` AS `a` ';
        $sql .= 'LEFT JOIN `sline_member_order` AS b ON(a.`ordersn` = b.`ordersn`) ';
        $sql .= 'LEFT JOIN `sline_model` AS `c` ON(a.`type_id` = c.`id`) ';
        $sql .= 'WHERE 1 = 1 ';
        if ($array['type_id'])
        {
            $sql .= 'AND a.`type_id` = ' . $array['type_id'] . ' ';
        }
        if ($array['channel_id'])
        {
            $sql .= 'AND b.`channel_id` = ' . $array['channel_id'] . ' ';
        }
        //线上支付
        if ($array['pay_method'] == 1)
        {
            $sql .= 'AND b.`online_transaction_no` != "" ';
        }
        //线下支付
        if ($array['pay_method'] == 2)
        {
            $sql .= 'AND b.`online_transaction_no` = "" ';
        }

        if (!empty($array['paysource'])) {
            $sql .= " AND b.paysource='{$array['paysource']}'";
        }

        if ($array['status'] != '')
        {
            $sql .= 'AND a.`status` = ' . $array['status'] . ' ';
        }
        if ($array['keyword'])
        {
            $sql .= "AND (a.`ordersn` LIKE '%{$array['keyword']}%' OR a.`linkman` LIKE '%{$array['keyword']}%' OR a.`linktel` LIKE '%{$array['keyword']}%') ";
        }

        if(empty($array['time_target']))
        {
            if (!empty($array['start_time'])) {
                $sql .= " and b.addtime>=".$array['start_time'];
            }
            if (!empty($array['end_time'])) {
                $sql .= " and b.addtime<=".$array['end_time'];
            }
        }
        //按支付时间
        else if($array['time_target']==1)
        {
            if (!empty($array['start_time'])) {
                $sql .= " and a.pay_time>=".$array['start_time'];
            }
            if (!empty($array['end_time'])) {
                $sql .= " and a.pay_time<=".$array['end_time'];
            }
        }

        $sql .=" order by a.id desc";
        if($array['limit']){
            $sql .= " LIMIT {$array['start']},{$array['limit']}";
        }

        $rows = DB::query(1, $sql)
                  ->execute()
                  ->as_array();


        return $rows;
    }

    /**
     * @function 获取收入详情
     * @param $id
     * @return mixed
     */
    public static function get_info($id)
    {
        $sql = 'SELECT a.`id`,a.`ordersn`,a.`type_id`,a.`amount`,a.`mid`,a.`pdt_type`,a.`pay_type`,';
        $sql .= 'a.`pdt_name`,a.`pay_time`,a.`status`,a.`operator`,a.`opt_time`,a.`amount`,';
        $sql .= 'c.`pinyin`,b.`id` AS `orderid`,';
        $sql .= 'b.`online_transaction_no` AS `pay_num`,';
        $sql .= 'b.`payment_proof` AS `pay_proof`,';
        $sql .= 'b.`saleman` AS `salesman`,';
        $sql .= 'b.`linkman`,';
        $sql .= 'b.`linktel`,';
        $sql .='mot.profit,mot.basicprice,mot.oldprofit,mot.oldbasicprice,mot.childprofit,mot.childbasicprice,mot.people4_profit,mot.people4_basicprice,mot.people5_profit,mot.people5_basicprice,mot.people6_profit,mot.people6_basicprice,b.dingnum,b.childnum,b.oldnum,b.people4_num,b.people5_num,b.people6_num,b.childprice,b.price,b.oldprice,b.people4_price,b.people5_price,b.people6_price,moc.privileg_price,b.express_total_price  ';
        $sql .= 'FROM `sline_platform_income` AS `a` ';
        $sql .= 'LEFT JOIN `sline_member_order` AS b ON(a.`ordersn` = b.`ordersn`) ';
        $sql .= 'LEFT JOIN `sline_member_order_extend` AS mot ON(mot.`orderid` = b.`id`) ';
        $sql .= 'LEFT JOIN `sline_member_order_compute` AS moc ON(moc.`order_id` = b.`id`) ';
        $sql .= 'LEFT JOIN `sline_model` AS `c` ON(a.`type_id` = c.`id`) ';
        $sql .= 'WHERE a.`id` = ' . $id;

        $info = DB::query(1, $sql)
                  ->execute()
                  ->current();

        $info['is_online'] = strpos($info['pay_type'], '线下支付') === false ? 1 : 0;

        return $info;
    }

    public static function income_excel($params){

        $titles = array('订单号','产品类别','支付时间','支付方式','支付渠道','联系人','联系人电话','营业收入','到账情况');
        $rows = array();
        $arr=Model_Finance_Income::get_search_list($params);
        foreach ($arr as $row)
        {
            $pay_type = $row['pay_type'] ? $row['pay_type'] : '-';
            $linkman = $row['linkman'] ? $row['linkman'] : '-';
            $linktel = $row['linktel'] ? $row['linktel'] : '-';
            $status = $row['status']==0 ? '待确认' : '已到账';
            $payway = $row['online_transaction_no'] ? '线上支付' : '线下支付';

            $rows[] = array(
                $row['ordersn'],
                $row['pdt_type'],
                $row['pay_time'] ? date('Y-m-d H:i:s', $row['pay_time']) : '--',
                $payway,
                $pay_type,
                $linkman,
                $linktel,
                $row['amount'],
                $status
            );
        }

        $td_width = array(25,10,20,20,15,25,15,10);
        $col_style = array('string','string','string','string','string','string','string');
        St_File::export_excel($rows, $titles, $td_width, $col_style);

    }
}